package p10;

public class SingletonDemo {
    private SingletonDemo() {}

//    private static SingletonDemo instance = null;

//    // 饿汉模式，现在方法区里创建静态实例
//    private static SingletonDemo instance = new SingletonDemo();
//    public static SingletonDemo getInstance() {
//        return instance;
//    }

//    // 线程安全的懒汉模式，但性能不高
//    public static synchronized SingletonDemo getInstance() {
//        if (instance == null) {
//            instance = new SingletonDemo();
//        }
//
//        return instance;
//    }

    // 双重验证锁，需要添加volatile来保证可见性可禁止指令重排序
    private volatile static SingletonDemo instance = null;

    public static SingletonDemo getInstance() {
        if (instance == null) {
            synchronized (SingletonDemo.class) {
                if (instance == null) {
                    instance = new SingletonDemo();
                }
            }
        }

        return instance;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                System.out.println(SingletonDemo.getInstance());
            }).start();
        }
    }
}
